from functools import wraps

from starlette.requests import Request

from app.providers.database import SessionLocal


def db_rollback_on_error(func):
    @wraps(func)
    def wrapper(req: Request, *args, **kwargs):
        db = SessionLocal()
        req.state.db = db
        try:
            response = func(req, *args, **kwargs)
        except Exception as e:

            db.rollback()
            raise
        else:
            db.commit()
        finally:
            db.close()
        return response

    return wrapper